﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using MyOS.Models;
using MyOS.Utils;
using MyOS.ViewModel;
using Panuon.UI.Silver;

namespace MyOS
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : WindowX
    {
        public delegate void Feedback();

        public static Dictionary<string, Type> _partialViewDic;

        static MainWindow()
        {
            _partialViewDic = new Dictionary<string, Type>();
            var assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.FullName.StartsWith("MyOS"));
            assembly.GetTypes().Where(x => x.IsSubclassOf(typeof(UserControl)))
                .ToList().ForEach(x => _partialViewDic.Add(x.Name.Remove(x.Name.Length - 4), x));
            // _partialViewDic.Add("CreateSystem",typeof(CreateSystemView));
        }

        public MainWindow()
        {
            InitializeComponent();
            ViewModel = new MainWindowViewModel();
            DataContext = ViewModel;
        }

        public MainWindowViewModel ViewModel { get; set; }

        private void MainWindow_OnClosing(object sender, CancelEventArgs e)
        {
            Application.Current.Shutdown();
            ;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
        }

        private void TvMenu_SelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (!IsLoaded)
                return;

            var selectedItem = TvMenu.SelectedItem as TreeViewItemModel;
            var tag = selectedItem.Tag;
            if (tag.IsNullOrEmpty())
                return;

            if (_partialViewDic.ContainsKey(tag))
            {
                var isCreated = IniUtils.Read("System", "IsCreated", "./config.ini").Equals("1");

                if (!isCreated)
                {
                    tag = "CreateSystem";
                    ContentControl.Content =
                        Activator.CreateInstance(_partialViewDic[tag], new Feedback(SuccessCreateSystemCallBack));
                }
                else
                {
                    ContentControl.Content =
                        Activator.CreateInstance(_partialViewDic[tag]);
                }
            }
            else
            {
                ContentControl.Content = null;
            }
        }

        private void SuccessCreateSystemCallBack()
        {
            ContentControl.Content = Activator.CreateInstance(_partialViewDic["VirtualAbout"]);
        }

        private void WindowX_Loaded(object sender, RoutedEventArgs e)
        {
        }

        private void WindowX_Closing(object sender, CancelEventArgs e)
        {
            Application.Current.Shutdown();
        }
    }
}